package com.eas.web.common.valve;

import static com.alibaba.citrus.turbine.util.TurbineUtil.getTurbineRunData;
import static com.alibaba.citrus.util.Assert.assertNotNull;

import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.citrus.service.pipeline.PipelineContext;
import com.alibaba.citrus.service.pipeline.support.AbstractValve;
import com.alibaba.citrus.turbine.Navigator;
import com.alibaba.citrus.turbine.TurbineRunData;
import com.eas.web.common.utils.WebUser;

public class AuthorizationValve extends AbstractValve {

    @Autowired
    private HttpServletRequest request;

    private Set<String> targetSet;

    public void invoke(PipelineContext pipelineContext) throws Exception {
        TurbineRunData rundata = getTurbineRunData(request);
        Navigator navi = (Navigator) rundata;
        String target = assertNotNull(rundata.getTarget(), "Target was not specified");
        if (!targetSet.contains(target)) {
            WebUser user = WebUser.getWebUser(rundata);
            if (!user.hasLogin()) {
                navi.redirectTo("loginURI");
            }
        }
        pipelineContext.invokeNext();
    }

    public Set<String> getTargetSet() {
        return targetSet;
    }

    public void setTargetSet(Set<String> targetSet) {
        this.targetSet = targetSet;
    }
}
